//
//  StatusCellPictureView.swift
//  MicroBlog
//
//  Created by  NorthCity on 15/11/10.
//  Copyright © 2015年  NorthCity. All rights reserved.
//

import UIKit
import SDWebImage
/// 图片间距
private let StatusCellPictureMargin:CGFloat =  8
/// 可重用表示符号
private let StatusPictureCellId = "StatusPictureCellId"

class StatusCellPictureView: UICollectionView {
    /// 微博视图模型
    var viewModel:StatusViewModel?{
        didSet{
            sizeToFit()
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    init(){
        let layout = UICollectionViewFlowLayout()
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        layout.minimumInteritemSpacing = StatusCellPictureMargin
        layout.minimumLineSpacing = StatusCellPictureMargin
        backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        //        注册可重用 cell
        registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: StatusPictureCellId)
        //        设置数据源方法
        dataSource = self
        delegate = self
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
//MARK: - 代理方法
extension StatusCellPictureView:UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(TcgStatusSelectedPhotoNotification, object: self, userInfo: [TcgStatusSelectedPhotoIndexPathKey:indexPath,
                             TcgStatusSelectedPhotoURLsKey:(viewModel?.thumbnailUrls)!])
        
        
    }
}
//MARK: - 数据源方法
extension StatusCellPictureView:UICollectionViewDataSource{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnailUrls?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell =  collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureCellId, forIndexPath: indexPath) as! StatusPictureCell
        
        cell.imageURL = viewModel?.thumbnailUrls![indexPath.item]
        return cell
    }
}
//MARK: - 实现转场动画协议
extension StatusCellPictureView:PictureBrowserPresentDelegate{
    
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView {
        let iv = UIImageView()
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        let key = viewModel!.thumbnailUrls![indexPath.item].absoluteString
        iv.image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        iv.sizeToFit()
        return iv
    }
    
    func pictureBrowserFromRect(indexPath: NSIndexPath) -> CGRect {
        guard let cell = self.cellForItemAtIndexPath(indexPath) else{
            return CGRectZero
        }
        let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        return rect
    }
    
    func pictureBrowserToRect(indexPath: NSIndexPath) -> CGRect {
        let key = viewModel!.thumbnailUrls![indexPath.item].absoluteString
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) else{
            return CGRectZero
        }
        let w = UIScreen.mainScreen().bounds.width
        let h = image.size.height * w / image.size.width
        var y:CGFloat = 0
        let height = UIScreen.mainScreen().bounds.height
        if height > h{
            y = (height - h) * 0.5
        }
        return CGRect(x: 0, y: y, width: w, height: h)
    }
    
}
//MARK: - 视图大小
extension StatusCellPictureView{
    //    MARK: - 计算视图大小
    private func calcViewSize()->CGSize{
        // 默认每行三张
        let rowCount:CGFloat  = 3
        let maxSize = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin
        let itemWidth = (maxSize - 2 * StatusCellPictureMargin) / rowCount - 0.01
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        // 图片数量
        let count = viewModel?.thumbnailUrls?.count ?? 0
        // 0 图
        if count == 0 {
            return CGSizeZero
        }
        // 1 图
        if count == 1{
            // TODO: - 临时图片大小
            var size = CGSizeMake(150, 120)
            // 内部图片的大小
            let key = viewModel!.thumbnailUrls![0].absoluteString
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) {
                size = image.size
                
                // 过窄处理 - 针对长图
                size.width = size.width < 40 ? 40 : size.width
                // 过宽的图片
                if size.width > 300 {
                    let w: CGFloat = 300
                    let h = size.height * w / size.width
                    
                    size = CGSize(width: w, height: h)
                }
                
                layout.itemSize = size
                
                return size
            }
        }
        // 4 图
        if count == 4{
            let w = 2 * itemWidth + StatusCellPictureMargin
            return CGSizeMake(w, w)
        }
        // 其余
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        let width = itemWidth * rowCount + (rowCount - 1) * StatusCellPictureMargin
        let height = itemWidth * row + (row - 1) * StatusCellPictureMargin
        return CGSizeMake(width, height)
    }
}


/// 微博配图 cell
private class StatusPictureCell:UICollectionViewCell{
    var imageURL:NSURL?{
        didSet{
            iconView.sd_setImageWithURL(
                imageURL,
                placeholderImage: nil,
                options:[SDWebImageOptions.RefreshCached,
                    SDWebImageOptions.RefreshCached
                ])
        }
    }
    //    MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI(){
        
        contentView.addSubview(iconView)
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    //  MARK: - 懒加载控件
    private lazy var iconView:UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()
    
}
